package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"grow-sys/cache"
	"grow-sys/model"
	"grow-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	rediskey := "login_" + username
	cachedata, _ := cache.Rdb.Get(cache.Ctx, rediskey).Int()
	if cachedata == 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，封禁2两小时",
		})
		return
	}
	var user model.User
	model.DB.Where("username=?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "该用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, rediskey)
		if cachedata == 2 {
			cache.Rdb.Set(cache.Ctx, rediskey, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	data := model.Article{
		Title:   title,
		Content: content,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var art []model.Article
	rediskey := "redis_list" + strconv.Itoa(page)
	cachedata, _ := cache.Rdb.Get(cache.Ctx, rediskey).Result()
	if cachedata == "" {
		model.DB.Offset(offset).Limit(size).Find(&art)
		jsondata, _ := json.Marshal(art)
		cache.Rdb.Set(cache.Ctx, rediskey, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachedata), &art)
	}
	var total int64
	model.DB.Table("articles").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  art,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.PostForm("id")
	var art model.Article
	rediskey := "redis_detail" + id
	cachedata, _ := cache.Rdb.Get(cache.Ctx, rediskey).Result()
	if cachedata == "" {
		model.DB.Where("id =?", id).Find(&art)
		jsondata, _ := json.Marshal(art)
		cache.Rdb.Set(cache.Ctx, rediskey, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachedata), &art)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": art,
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	model.DB.Where("id =?", id).Delete(&model.Article{})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
